package com.bfc.demo;

import java.util.Objects;

public class MyHashMap<K, V> implements MyMap<K, V> {

	// 默认长度
	private static int length = 16;
	// 加载因子
	private static double load = 0.75;
	// value 数组
	private Entry<K, V>[] table = null;
	// map 大小
	private int size;

	@SuppressWarnings({ "static-access", "unchecked" })
	public MyHashMap(int length, double load) {
		this.length = length;
		this.load = load;
		table=new Entry[length];
	}

	public MyHashMap() {
		this(length, load);
	}

	@Override
	public Boolean put(K k, V v) {
		int index=getIndex(k);
		Entry<K, V> e=table[index];
		if (e!=null) {
			while (e.hasNext()) {
				if (e.getKey().hashCode()==k.hashCode()&&Objects.equals(e.getKey(), k)) {
					return false;
				}
			}
		}
		table[index]=new Entry<K, V>(k, v, e, index);
		size++;
		return true;
	}


	@Override
	public V get(K k) {
		int index = getIndex(k);
		Entry<K, V> entry=table[index];
		if (entry==null) {
			return null;
		}
		while (entry.hasNext()) {
			if (entry.getKey().hashCode()==k.hashCode() && Objects.equals(entry.getKey(), k)) {
				return entry.getValue();
			}
			entry=entry.getNext();
		}
		return entry.getValue();
	}

	@Override
	public int size() {
		return size;
	}
	
	private int getIndex(K k) {
		return k.hashCode()%(length-1);
	}
	

	@SuppressWarnings("hiding")
	class Entry<K, V> implements MyMap.Entry<K, V> {

		K k;
		V v;
		Entry<K, V> next;
		int index;
		
		public Entry(K k, V v, Entry<K, V> next, int index) {
			super();
			this.k = k;
			this.v = v;
			this.next = next;
			this.index = index;
		}

		@Override
		public boolean hasNext() {
			if (next!=null) {
				return true;
			}
			return false;
		}

		@Override
		public K getKey() {
			return k;
		}

		@Override
		public V getValue() {
			return v;
		}
		
		Entry<K, V> getNext(){
			return next;
		}
		
	}

}
